<template>
  <div class="todo-footer">
    <label>
      <input type="checkbox" v-model="checkAll" :disabled="disabled" />
    </label>
    <span
      ><span>已完成{{ computedCount }} </span> / 全部{{ tasks.length }}</span
    >
    <button class="btn btn-danger" @click="clear">清除已完成任务</button>
  </div>
</template>

<script>
export default {
  name: 'v-footer',
  props: ['tasks'],
  methods: {
    //清除已完成任务
    clear() {
      this.$bus.$emit('clear');
    },
  },
  computed: {
    //全选按钮是否要禁用
    disabled() {
      return this.tasks.length === 0 && this.computedCount === 0;
    },

    //全选全不选
    checkAll: {
      get() {
        //当已完成的数量等于全部的数量时 全选按钮需要选中(剔除他们都等于0的情况)
        return (
          this.tasks.length === this.computedCount &&
          this.tasks.length !== 0 &&
          this.computedCount !== 0
        );
      },
      set(checked) {
        //拿到全选的最新状态  交给app 将所有任务的状态切换为当前全选按钮的状态
        this.$bus.$emit('checkAll', checked);
      },
    },

    //已完成的数量
    computedCount() {
      return this.tasks.reduce(
        (adder, task) => (task.checked ? adder + 1 : adder),
        0
      );
    },
  },
};
</script>

<style scoped>
input[disabled] {
  cursor: not-allowed;
}

.todo-footer {
  height: 40px;
  line-height: 40px;
  padding-left: 6px;
  margin-top: 5px;
}

.todo-footer label {
  display: inline-block;
  margin-right: 20px;
  cursor: pointer;
}

.todo-footer label input {
  position: relative;
  top: -1px;
  vertical-align: middle;
  margin-right: 5px;
}

.todo-footer button {
  float: right;
  margin-top: 5px;
}
</style>
